import {
    store
} from '../store/index.js'
import i18n from '../lang/index.js'
export default {
    install(Vue) {
        // const serve = 'https://test.global3plus.com'
        // const serve = 'https://app.global3plus.com'
        // const serve = 'http://www.jingziy.cn'
        // Vue.prototype.$app='wx1f3e51f665a140fd'
        Vue.prototype.$save = function(key, data) {
            uni.setStorage({
                key,
                data
            })
        }
        Vue.prototype.$get = function(key) {
            return uni.getStorageSync(key)
        }
        Vue.prototype.$http = function(_url, data = {}) {
            // uni.showLoading({
            //     title: i18n.t('loading')
            // })
            let [method, url] = _url.split('|')
            const tokenKey = store.state.__key_token
            const userIdKey = store.state.__key_user_id
            method = method.toUpperCase()

            const header = {
                // #ifndef H5
                Cookie: uni.getStorageSync(tokenKey) ? 'PHPSESSID=' + uni.getStorageSync(tokenKey) : ''
                // #endif
            }
            return new Promise((resolve, reject) => {
                if (/https/.test(url)) {
                    //
                    console.log('https:', url)
                } else {
                    // #ifdef H5
                    url = `/${url}`
                    // #endif
                    // #ifdef APP-PLUS
                    url = `${store.state.$server}/${url}`
                    // #endif
                }
                const user_id = uni.getStorageSync(userIdKey) || ''
                if (user_id) {
                    data.user_id = user_id
                }
                // console.log('$http', url, header)
                uni.request({
                    url: url,
                    method,
                    dataType: 'json',
                    timeout: 8000,
                    responseType: 'text',
                    header,
                    data,
                    success: (res) => {
                        // console.log(url, res)
                        uni.hideLoading()
                        if (res.data.status === 1) {
                            resolve(res.data)
                        } else {
                            if (res.data.status === -100 || res.data.status === -103) {
                                store.commit('logout')
                                reject(res.data)
                            } else if (typeof res.data !== 'object' && typeof res.data === 'string') {
                                // 系统错误
                                // this.$toastApp(res.data)
                                reject(res.data)
                            } else {
                                // this.$toastApp(res.data.msg)
                                reject(res.data)
                            }
                        }
                    },
                    fail: (err) => {
                        // console.log('fail', url, err)
                        reject(err)
                    }
                })
            })
        }
        Vue.prototype.$navigateTo = function(url) {
            if (this.$store.state.isLogin) {
                if (url !== '/pages/login') {
                    if (typeof url !== 'string') {
                        uni.navigateTo(url)
                    } else {
                        uni.navigateTo({
                            url
                        })
                    }
                }
            } else {
                uni.navigateTo({
                    url: '/pages/login'
                })
            }
        }
        Vue.prototype.$alert = function(title, icon) {
            uni.showToast({
                icon,
                title
            })
        }
        Vue.prototype.noScroll = function() {
            // #ifdef H5
            document.body.style.overflowY = 'hidden'
            // #endif
        }
        Vue.prototype.remScroll = function() {
            // #ifdef H5
            document.body.style.overflowY = 'auto'
            // #endif
        }
        Vue.prototype.$init = function(callback, code) {
            let data = {}
            if (code) {
                data = {
                    code: code
                }
            }
            return this.$http('get|api/MobileBase/gzhdoLogin', data)
                .then((res) => {
                    callback(res)
                })
                .catch((err) => {
                    if (err.status === -101) {
                        // 绑定手机
                        this.show_bind = true
                        // console.log("绑定手机号");
                    }
                    if (err.status === -102) {
                        // console.log("失败");
                        // 授权失败
                    }
                })
        }
        Vue.prototype.$get_appId = async function(jsApiList, callbakc, bool = false, askUrl = window.location.href) {
            await this.$http('post|api/MobileBase/ajaxGetWxConfig', {
                // askUrl: encodeURIComponent(askUrl)
                askUrl: encodeURIComponent('https://app.global3plus.com/h5/#/index/create_order/')
            }).then(async (res) => {
                await $wx.config({
                    debug: bool, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                    appId: res.result.appId, // 必填，公众号的唯一标识
                    timestamp: res.result.timestamp, // 必填，生成签名的时间戳
                    nonceStr: res.result.nonceStr, // 必填，生成签名的随机串
                    signature: res.result.signature, // 必填，签名
                    jsApiList: jsApiList
                })
                $wx.ready(() => {
                    // 需在用户可能点击分享按钮前就先调用
                    callbakc()
                })
            })
        }
        Vue.prototype.$login = function() {
            uni.showModal({
                title: '提示',
                content: '您还未登录',
                confirmText: '去登录',
                confirmColor: '#4E6EF3',
                success: function(res) {
                    if (res.confirm) {
                        uni.setStorageSync('showLogin', false)
                        uni.navigateTo({
                            url: '/pages/login'
                        })
                    } else if (res.cancel) {
                        uni.setStorageSync('showLogin', false)
                    }
                }
            })
        }
        Vue.prototype.$check_mobel = function(mobel) {
            return /^\d{6,}$/.test(mobel)
        }
        Vue.prototype.$copy = function(val) {
            // #ifdef H5
            const textarea = document.createElement('textarea')
            textarea.value = val
            textarea.style.position = 'fixed'
            textarea.style.zIndex = '-999'
            textarea.style.top = 0
            document.body.appendChild(textarea)
            textarea.select()
            document.execCommand('copy')
            this.$toastApp('复制成功')
            document.body.removeChild(textarea)
            // #endif
            // #ifndef H5
            uni.setClipboardData({
                data: val,
                success() {
                    // this.$toastApp('复制成功');
                }
            })
            // #endif
        }
        Vue.prototype.$uploadFile = function(file) {
            return new Promise((resolve, reject) => {
                // let size = file.tempFiles[0].size / 1024 / 1024;
                // let fileUrl = "";
                let $server = ''
                // #ifdef APP-PLUS
                $server = store.state.$server
                // #endif
                uni.uploadFile({
                    url: $server + '/api/Api/add_identification',
                    filePath: file.tempFilePaths[0],
                    name: 'identification',
                    success: (res) => {
                        const dataRes = JSON.parse(res.data)
                        if (dataRes.status === 1) {
                            resolve(dataRes)
                        } else {
                            reject(dataRes.msg)
                        }
                    },
                    fail: () => {
                        // eslint-disable-next-line
                        reject('上传失败请重试')
                    }
                })
            })
        }
        Vue.prototype.$uploadCom = function(file) {
            return new Promise((resolve, reject) => {
                // let size = file.tempFiles[0].size / 1024 / 1024;
                // let fileUrl = "";
                let $server = ''
                // #ifdef APP-PLUS
                $server = store.state.$server
                // #endif
                uni.uploadFile({
                    url: $server + '/api/Api/add_company_certificate',
                    filePath: file.tempFilePaths[0],
                    name: 'company',
                    success: (res) => {
                        const dataRes = JSON.parse(res.data)
                        if (dataRes.status === 1) {
                            resolve(dataRes)
                        } else {
                            reject(dataRes.msg)
                        }
                    },
                    fail: () => {
                        // eslint-disable-next-line
                        reject('上传失败请重试')
                    }
                })
            })
        }
        Vue.prototype.$uploadHeader = function(file) {
            return new Promise((resolve, reject) => {
                uni.showLoading({
                    title: i18n.t('loading')
                })
                let $server = ''
                // #ifdef APP-PLUS
                $server = store.state.$server
                // #endif
                uni.uploadFile({
                    url: $server + '/api/Api/head_pic',
                    filePath: file,
                    name: 'head_pic',
                    success: (res) => {
                        const dataRes = JSON.parse(res.data)
                        if (dataRes.status === 1) {
                            resolve(dataRes)
                        } else {
                            reject(dataRes.msg)
                        }
                    },
                    fail: () => {
                        // eslint-disable-next-line
                        reject('上传失败请重试')
                    },
                    complete() {
                        uni.hideLoading()
                    }
                })
                // }
            })
        }
        Vue.prototype.$toast = function(msg, ok, mask, fail) {
            uni.showToast({
                title: msg,
                icon: 'none',
                mask: mask || false,
                duration: 1500,
                position: 'bottom',
                success: ok,
                fail: fail
            })
        }
        Vue.prototype.$toastApp = function(msg) {
            // #ifdef APP-PLUS
            plus.nativeUI.toast(msg)
            // #endif
            // #ifndef APP-PLUS
            this.$toast(msg)
            // #endif
        }
    }
}
